// 应用主要JavaScript功能

// 检查模型状态
function checkModelsStatus() {
    const modal = new bootstrap.Modal(document.getElementById('modelsModal'));
    const modalBody = document.getElementById('modelsModalBody');
    
    // 显示加载状态
    modalBody.innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在检查模型状态...</p>
        </div>
    `;
    
    modal.show();
    
    // 获取模型状态
    fetch('/models/status')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                modalBody.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${data.error}
                    </div>
                `;
            } else {
                displayModelsStatus(data);
            }
        })
        .catch(error => {
            modalBody.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    网络错误: ${error.message}
                </div>
            `;
        });
}

// 显示模型状态
function displayModelsStatus(status) {
    const modalBody = document.getElementById('modelsModalBody');
    
    let html = '<div class="row">';
    
    for (const [modelName, modelStatus] of Object.entries(status)) {
        const statusClass = modelStatus.available ? 'success' : 'danger';
        const statusIcon = modelStatus.available ? 'check-circle' : 'times-circle';
        const statusText = modelStatus.available ? '已下载' : '未下载';
        
        html += `
            <div class="col-md-6 mb-3">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">
                            <i class="fas fa-${statusIcon} text-${statusClass} me-2"></i>
                            ${modelName}
                        </h6>
                        <p class="card-text">
                            <small class="text-muted">状态: ${statusText}</small>
                        </p>
                        ${modelStatus.size ? `<p class="card-text"><small class="text-muted">大小: ${modelStatus.size}</small></p>` : ''}
                    </div>
                </div>
            </div>
        `;
    }
    
    html += '</div>';
    modalBody.innerHTML = html;
}

// 下载模型
function downloadModels() {
    const modalBody = document.getElementById('modelsModalBody');
    
    // 显示下载进度
    modalBody.innerHTML = `
        <div class="text-center">
            <div class="spinner-border" role="status">
                <span class="visually-hidden">下载中...</span>
            </div>
            <p class="mt-2">正在下载模型，请稍候...</p>
            <div class="progress mt-3">
                <div class="progress-bar progress-bar-striped progress-bar-animated" 
                     role="progressbar" style="width: 100%"></div>
            </div>
        </div>
    `;
    
    // 发送下载请求
    fetch('/models/download', {
        method: 'POST'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                modalBody.innerHTML = `
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        ${data.message}
                    </div>
                `;
                // 重新检查状态
                setTimeout(() => {
                    checkModelsStatus();
                }, 2000);
            } else {
                modalBody.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${data.error}
                    </div>
                `;
            }
        })
        .catch(error => {
            modalBody.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    网络错误: ${error.message}
                </div>
            `;
        });
}

// 文件拖拽上传功能
document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.getElementById('fileInput');
    const uploadForm = document.getElementById('uploadForm');
    
    if (fileInput && uploadForm) {
        // 防止默认拖拽行为
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadForm.addEventListener(eventName, preventDefaults, false);
            document.body.addEventListener(eventName, preventDefaults, false);
        });
        
        // 高亮拖拽区域
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadForm.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            uploadForm.addEventListener(eventName, unhighlight, false);
        });
        
        // 处理文件拖拽
        uploadForm.addEventListener('drop', handleDrop, false);
    }
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

function highlight(e) {
    e.currentTarget.classList.add('border-primary', 'bg-light');
}

function unhighlight(e) {
    e.currentTarget.classList.remove('border-primary', 'bg-light');
}

function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    
    if (files.length > 0) {
        const fileInput = document.getElementById('fileInput');
        fileInput.files = files;
        
        // 触发文件选择事件
        const event = new Event('change', { bubbles: true });
        fileInput.dispatchEvent(event);
    }
}

// 文件大小格式化
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        // 显示成功提示
        showToast('已复制到剪贴板', 'success');
    }, function(err) {
        console.error('复制失败: ', err);
        showToast('复制失败', 'error');
    });
}

// 显示提示消息
function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'success' ? 'success' : 'primary'} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    // 自动移除
    toast.addEventListener('hidden.bs.toast', function() {
        toast.remove();
    });
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    document.body.appendChild(container);
    return container;
}
